package api

import (
	"fmt"
	"im-demo/application/service"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

// 将http协议升级为websocket协议
func WsHandler(c *gin.Context, m *service.Manager) {
	uid := c.Query("uid")
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		http.NotFound(c.Writer, c.Request)
		return
	}

	client := &service.Client{
		Uid:     uid,
		Manager: m,
		Conn:    conn,
		Send:    make(chan []byte, 256),
	}

	fmt.Println("有用户上线：", uid)

	client.Manager.Register <- client

	// new goroutines.
	go client.WritePump()
	go client.ReadPump()
}
